package net.maku.newbase.annotation.result.aop;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.SneakyThrows;
import net.maku.newbase.R;
import net.maku.newbase.annotation.result.RDataToVO;
import net.maku.newbase.annotation.result.RDataType;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.List;

@Aspect
@Component
public class REntityToVOAspect {

    @Pointcut("@annotation(net.maku.newbase.annotation.result.RDataToVO)")
    public void PointCut() {

    }

    @Before("PointCut()")
    public void Before() {
    }

    @SneakyThrows
    @Around("PointCut()")
    public R Around(ProceedingJoinPoint pjp) {
        R r = (R) pjp.proceed();
        //获取注解参数
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Method method = methodSignature.getMethod();

        return fn(r, method.getAnnotation(RDataToVO.class));
    }

    @After("PointCut()")
    public void After() {
    }

    @AfterReturning("PointCut()")
    public void AfterReturning() {
    }

    private R fn(R r, RDataToVO annotation) {
        if (annotation.type() == RDataType.ENTITY) return fnEntity(r, annotation);
        if (annotation.type() == RDataType.LIST) return fnList(r, annotation);
        if (annotation.type() == RDataType.PAGE) return fnPage(r, annotation);
        return r;
    }

    private R fnPage(R r, RDataToVO annotation) {
        IPage iPage = (IPage) r.get("data");
        List list = iPage.getRecords();
        if (list.size() > 0) {
            iPage.setRecords(JSONArray.parseArray(JSONArray.toJSONString(list), annotation.c()));
            r.put("data", iPage);
        }
        return r;
    }

    private R fnList(R r, RDataToVO annotation) {
        List list = (List) r.get("data");
        if (list.size() > 0) {
            List l = JSONArray.parseArray(JSONArray.toJSONString(list), annotation.c());
            r.put("data", l);
        }
        return r;
    }

    private R fnEntity(R r, RDataToVO annotation) {
        r.put("data", JSONObject.parseObject(JSONObject.toJSONString(r.get("data")), annotation.c()));
        return r;
    }

}
